/*
 * Copyright 2007 Brian Watkins
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */


package bw.cal;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.text.*;
import bw.util.*;
import bw.note.*;
import bw.os.*;

public class EventServlet extends HttpServlet
{
    public static final String AGENDA_START_DATE = "AGENDA-START-DATE";
    public static final String AGENDA_NUM_DAYS = "AGENDA-NUM-DAYS";

    public static final String ACTION = "action";
    public static final String SAVE_EVENT = "saveEvent";
    public static final String GET_EVENTS = "getEvents";
    public static final String LOOKUP_EVENTS = "lookupEvents";
    public static final String DELETE_EVENT = "deleteEvent";

    public static final String EVENT_TYPE = "eventType";
    public static final String EVENT_DATE = "eventDate";
    public static final String EVENT_START = "eventStart";
    public static final String EVENT_END = "eventEnd";
    public static final String EVENT_DESC = "eventDesc";
    public static final String EVENT_ID = "eventId";
    public static final String NUM_DAYS = "numDays";
    public static final String RETURN_EVENTS = "returnEvents";
    
    public static final String CURRENT_DATE = "currentDate";

    public void doGet ( HttpServletRequest req, HttpServletResponse res )
        throws ServletException, IOException
    {
        CalendarEventManager manager = CalendarEventManager.getInstance();

        String action = req.getParameter( ACTION );
        String eventDate = req.getParameter( EVENT_DATE );

        HttpSession session = req.getSession();

        int numDays = 1;
        String numDaysStr = null;
        if ( ( numDaysStr = (String) session.getAttribute( AGENDA_NUM_DAYS ) ) != null )
        {
            numDays = Integer.parseInt( numDaysStr );
        }
        String startDate = (String) session.getAttribute( AGENDA_START_DATE );
        
        if ( SAVE_EVENT.equals( action ) )
        {
            int eventId = -1;
            String evtIdStr = req.getParameter( EVENT_ID );
            if ( evtIdStr != null && evtIdStr.length() > 0 )
            {
                eventId = Integer.parseInt( evtIdStr );
            }
            int eventType = Integer.parseInt( req.getParameter( EVENT_TYPE ) );
            String eventStart = req.getParameter( EVENT_START );
            String eventEnd = req.getParameter( EVENT_END );
            String eventDesc = req.getParameter( EVENT_DESC );

            CalendarEventTime time = CalendarEventTime.construct( eventDate, 
                                                                  eventStart, 
                                                                  eventEnd );
            CalendarEvent evt = new CalendarEvent( eventType, time, eventDesc );

            //if we have an id then get the old event from the CalDate
            //and remove it from the manager
            //NOTE: By removing the old event and adding the new we will
            //write to the ObjectStore twice (inside CalendarEventManager).
            //but this is ok -- we need to do this to handle the case where
            //the event type is updated, since CEM stores by event type.
            if ( eventId > -1 )
            {
                CalendarDate oCd = manager.getCalendarDate( eventDate );
                manager.removeEvent( oCd.removeEvent( eventId ) );
            }

            manager.addEvent( evt );
        }
        else if ( GET_EVENTS.equals( action ) )
        {
            String nDaysStr = req.getParameter( NUM_DAYS );
            if ( nDaysStr != null && nDaysStr.length() > 0 )
            {
                session.setAttribute( AGENDA_NUM_DAYS, nDaysStr );
                numDays = Integer.parseInt( nDaysStr );
            }
            else 
            {
                session.setAttribute( AGENDA_NUM_DAYS, "1" );
                numDays = 1;
            }

            session.setAttribute( AGENDA_START_DATE, eventDate );
            startDate = eventDate;
        }
        else if ( LOOKUP_EVENTS.equals( action ) )
        {
            //don't store the numdays or startDate in the session.
            //we just use this action to lookup event data -- used 
            //when getting data to edit an event and when looking up
            //events to display on the home page.
            numDays = 1;

            String nDaysStr = req.getParameter( NUM_DAYS );
            if ( nDaysStr != null && nDaysStr.length() > 0 )
            {
                numDays = Integer.parseInt( nDaysStr );
            }

            startDate = eventDate;
        }        
        else if ( DELETE_EVENT.equals( action ) )
        {
            int eventId = Integer.parseInt( req.getParameter( EVENT_ID ) );

            CalendarDate cd = manager.getCalendarDate( eventDate );
            
            manager.removeEvent( cd.removeEvent( eventId ) );
        }

        //get the cal dates using the start date and numDays params
        Vector calDates = new Vector();
        
        if ( !"false".equalsIgnoreCase( req.getParameter( RETURN_EVENTS ) ) ) 
        {
            if ( CURRENT_DATE.equals( startDate ) )
            {
                calDates = manager.getCalendarDates( DateFactory.getInstance().getDate(), 
                                                     numDays );
            }
            else
            {
                calDates = manager.getCalendarDates( startDate, numDays );
            }
        }

        res.setContentType( "text/xml" );
        
        PrintWriter out = res.getWriter();
        
        out.println( "<calendarDates>" );

        for ( Enumeration e = calDates.elements(); e.hasMoreElements(); )
        {
            CalendarDate calDate = (CalendarDate) e.nextElement();
            out.println( calDate );
        }

        out.println( "</calendarDates>" );
        
        out.close();
    }
}